Move page tweaks:
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 /**
3 * See title.txt
4 *
5 * @package MediaWiki
6 */
7
8 /** */
9 require_once( 'normal/UtfNormal.php' );
10
11 $wgTitleInterwikiCache = array();
12 define ( 'GAID_FOR_UPDATE', 1 );
13
14 # Title::newFromTitle maintains a cache to avoid
15 # expensive re-normalization of commonly used titles.
16 # On a batch operation this can become a memory leak
17 # if not bounded. After hitting this many titles,
18 # reset the cache.
19 define( 'MW_TITLECACHE_MAX', 1000 );
20
21 /**
22 * Title class
23 * - Represents a title, which may contain an interwiki designation or namespace
24 * - Can fetch various kinds of data from the database, albeit inefficiently.
25 *
26 * @package MediaWiki
27 */
28 class Title {
29 /**
30 * All member variables should be considered private
31 * Please use the accessor functions
32 */
33
34 /**#@+
35 * @access private
36 */
37
38 var $mTextform; # Text form (spaces not underscores) of the main part
39 var $mUrlform; # URL-encoded form of the main part
40 var $mDbkeyform; # Main part with underscores
41 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
42 var $mInterwiki; # Interwiki prefix (or null string)
43 var $mFragment; # Title fragment (i.e. the bit after the #)
44 var $mArticleID; # Article ID, fetched from the link cache on demand
45 var $mRestrictions; # Array of groups allowed to edit this article
46 # Only null or "sysop" are supported
47 var $mRestrictionsLoaded; # Boolean for initialisation on demand
48 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
49 var $mDefaultNamespace; # Namespace index when there is no namespace
50 # Zero except in {{transclusion}} tags
51 /**#@-*/
52
53
54 /**
55 * Constructor
56 * @access private
57 */
58 /* private */ function Title() {
59 $this->mInterwiki = $this->mUrlform =
60 $this->mTextform = $this->mDbkeyform = '';
61 $this->mArticleID = -1;
62 $this->mNamespace = NS_MAIN;
63 $this->mRestrictionsLoaded = false;
64 $this->mRestrictions = array();
65 # Dont change the following, NS_MAIN is hardcoded in several place
66 # See bug #696
67 $this->mDefaultNamespace = NS_MAIN;
68 }
69
70 /**
71 * Create a new Title from a prefixed DB key
72 * @param string $key The database key, which has underscores
73 * instead of spaces, possibly including namespace and
74 * interwiki prefixes
75 * @return Title the new object, or NULL on an error
76 * @static
77 * @access public
78 */
79 /* static */ function newFromDBkey( $key ) {
80 $t = new Title();
81 $t->mDbkeyform = $key;
82 if( $t->secureAndSplit() )
83 return $t;
84 else
85 return NULL;
86 }
87
88 /**
89 * Create a new Title from text, such as what one would
90 * find in a link. Decodes any HTML entities in the text.
91 *
92 * @param string $text the link text; spaces, prefixes,
93 * and an initial ':' indicating the main namespace
94 * are accepted
95 * @param int $defaultNamespace the namespace to use if
96 * none is specified by a prefix
97 * @return Title the new object, or NULL on an error
98 * @static
99 * @access public
100 */
101 function &newFromText( $text, $defaultNamespace = NS_MAIN ) {
102 $fname = 'Title::newFromText';
103 wfProfileIn( $fname );
104
105 if( is_object( $text ) ) {
106 wfDebugDieBacktrace( 'Title::newFromText given an object' );
107 }
108
109 /**
110 * Wiki pages often contain multiple links to the same page.
111 * Title normalization and parsing can become expensive on
112 * pages with many links, so we can save a little time by
113 * caching them.
114 *
115 * In theory these are value objects and won't get changed...
116 */
117 static $titleCache = array();
118 if( $defaultNamespace == NS_MAIN && isset( $titleCache[$text] ) ) {
119 wfProfileOut( $fname );
120 return $titleCache[$text];
121 }
122
123 /**
124 * Convert things like &eacute; into real text...
125 */
126 global $wgInputEncoding;
127 $filteredText = do_html_entity_decode( $text, ENT_COMPAT, $wgInputEncoding );
128
129 /**
130 * Convert things like &#257; or &#x3017; into real text...
131 * WARNING: Not friendly to internal links on a latin-1 wiki.
132 */
133 $filteredText = wfMungeToUtf8( $filteredText );
134
135 # What was this for? TS 2004-03-03
136 # $text = urldecode( $text );
137
138 $t =& new Title();
139 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
140 $t->mDefaultNamespace = $defaultNamespace;
141
142 if( $t->secureAndSplit() ) {
143 if( $defaultNamespace == NS_MAIN ) {
144 if( count( $titleCache ) >= MW_TITLECACHE_MAX ) {
145 # Avoid memory leaks on mass operations...
146 $titleCache = array();
147 }
148 $titleCache[$text] =& $t;
149 }
150 wfProfileOut( $fname );
151 return $t;
152 } else {
153 wfProfileOut( $fname );
154 return NULL;
155 }
156 }
157
158 /**
159 * Create a new Title from URL-encoded text. Ensures that
160 * the given title's length does not exceed the maximum.
161 * @param string $url the title, as might be taken from a URL
162 * @return Title the new object, or NULL on an error
163 * @static
164 * @access public
165 */
166 /* static */ function newFromURL( $url ) {
167 global $wgLang, $wgServer;
168 $t = new Title();
169
170 # For compatibility with old buggy URLs. "+" is not valid in titles,
171 # but some URLs used it as a space replacement and they still come
172 # from some external search tools.
173 $s = str_replace( '+', ' ', $url );
174
175 $t->mDbkeyform = str_replace( ' ', '_', $s );
176 if( $t->secureAndSplit() ) {
177 return $t;
178 } else {
179 return NULL;
180 }
181 }
182
183 /**
184 * Create a new Title from an article ID
185 * @todo This is inefficiently implemented, the page row is requested
186 * but not used for anything else
187 * @param int $id the page_id corresponding to the Title to create
188 * @return Title the new object, or NULL on an error
189 * @access public
190 */
191 /* static */ function newFromID( $id ) {
192 $fname = 'Title::newFromID';
193 $dbr =& wfGetDB( DB_SLAVE );
194 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
195 array( 'page_id' => $id ), $fname );
196 if ( $row !== false ) {
197 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
198 } else {
199 $title = NULL;
200 }
201 return $title;
202 }
203
204 /**
205 * Create a new Title from a namespace index and a DB key.
206 * It's assumed that $ns and $title are *valid*, for instance when
207 * they came directly from the database or a special page name.
208 * For convenience, spaces are converted to underscores so that
209 * eg user_text fields can be used directly.
210 *
211 * @param int $ns the namespace of the article
212 * @param string $title the unprefixed database key form
213 * @return Title the new object
214 * @static
215 * @access public
216 */
217 /* static */ function &makeTitle( $ns, $title ) {
218 $t =& new Title();
219 $t->mInterwiki = '';
220 $t->mFragment = '';
221 $t->mNamespace = IntVal( $ns );
222 $t->mDbkeyform = str_replace( ' ', '_', $title );
223 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
224 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
225 $t->mTextform = str_replace( '_', ' ', $title );
226 return $t;
227 }
228
229 /**
230 * Create a new Title frrom a namespace index and a DB key.
231 * The parameters will be checked for validity, which is a bit slower
232 * than makeTitle() but safer for user-provided data.
233 * @param int $ns the namespace of the article
234 * @param string $title the database key form
235 * @return Title the new object, or NULL on an error
236 * @static
237 * @access public
238 */
239 /* static */ function makeTitleSafe( $ns, $title ) {
240 $t = new Title();
241 $t->mDbkeyform = Title::makeName( $ns, $title );
242 if( $t->secureAndSplit() ) {
243 return $t;
244 } else {
245 return NULL;
246 }
247 }
248
249 /**
250 * Create a new Title for the Main Page
251 * @static
252 * @return Title the new object
253 * @access public
254 */
255 /* static */ function newMainPage() {
256 return Title::newFromText( wfMsgForContent( 'mainpage' ) );
257 }
258
259 /**
260 * Create a new Title for a redirect
261 * @param string $text the redirect title text
262 * @return Title the new object, or NULL if the text is not a
263 * valid redirect
264 * @static
265 * @access public
266 */
267 /* static */ function newFromRedirect( $text ) {
268 global $wgMwRedir;
269 $rt = NULL;
270 if ( $wgMwRedir->matchStart( $text ) ) {
271 if ( preg_match( '/\\[\\[([^\\]\\|]+)[\\]\\|]/', $text, $m ) ) {
272 # categories are escaped using : for example one can enter:
273 # #REDIRECT [[:Category:Music]]. Need to remove it.
274 if ( substr($m[1],0,1) == ':') {
275 # We don't want to keep the ':'
276 $m[1] = substr( $m[1], 1 );
277 }
278
279 $rt = Title::newFromText( $m[1] );
280 # Disallow redirects to Special:Userlogout
281 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL && preg_match( '/^Userlogout/i', $rt->getText() ) ) {
282 $rt = NULL;
283 }
284 }
285 }
286 return $rt;
287 }
288
289 #----------------------------------------------------------------------------
290 # Static functions
291 #----------------------------------------------------------------------------
292
293 /**
294 * Get the prefixed DB key associated with an ID
295 * @param int $id the page_id of the article
296 * @return Title an object representing the article, or NULL
297 * if no such article was found
298 * @static
299 * @access public
300 */
301 /* static */ function nameOf( $id ) {
302 $fname = 'Title::nameOf';
303 $dbr =& wfGetDB( DB_SLAVE );
304
305 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
306 if ( $s === false ) { return NULL; }
307
308 $n = Title::makeName( $s->page_namespace, $s->page_title );
309 return $n;
310 }
311
312 /**
313 * Get a regex character class describing the legal characters in a link
314 * @return string the list of characters, not delimited
315 * @static
316 * @access public
317 */
318 /* static */ function legalChars() {
319 # Missing characters:
320 # * []|# Needed for link syntax
321 # * % and + are corrupted by Apache when they appear in the path
322 #
323 # % seems to work though
324 #
325 # The problem with % is that URLs are double-unescaped: once by Apache's
326 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
327 # Our code does not double-escape to compensate for this, indeed double escaping
328 # would break if the double-escaped title was passed in the query string
329 # rather than the path. This is a minor security issue because articles can be
330 # created such that they are hard to view or edit. -- TS
331 #
332 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
333 # this breaks interlanguage links
334
335 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF";
336 return $set;
337 }
338
339 /**
340 * Get a string representation of a title suitable for
341 * including in a search index
342 *
343 * @param int $ns a namespace index
344 * @param string $title text-form main part
345 * @return string a stripped-down title string ready for the
346 * search index
347 */
348 /* static */ function indexTitle( $ns, $title ) {
349 global $wgDBminWordLen, $wgContLang;
350 require_once( 'SearchEngine.php' );
351
352 $lc = SearchEngine::legalSearchChars() . '&#;';
353 $t = $wgContLang->stripForSearch( $title );
354 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
355 $t = strtolower( $t );
356
357 # Handle 's, s'
358 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
359 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
360
361 $t = preg_replace( "/\\s+/", ' ', $t );
362
363 if ( $ns == NS_IMAGE ) {
364 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
365 }
366 return trim( $t );
367 }
368
369 /*
370 * Make a prefixed DB key from a DB key and a namespace index
371 * @param int $ns numerical representation of the namespace
372 * @param string $title the DB key form the title
373 * @return string the prefixed form of the title
374 */
375 /* static */ function makeName( $ns, $title ) {
376 global $wgContLang;
377
378 $n = $wgContLang->getNsText( $ns );
379 if ( '' == $n ) { return $title; }
380 else { return $n.':'.$title; }
381 }
382
383 /**
384 * Returns the URL associated with an interwiki prefix
385 * @param string $key the interwiki prefix (e.g. "MeatBall")
386 * @return the associated URL, containing "$1", which should be
387 * replaced by an article title
388 * @static (arguably)
389 * @access public
390 */
391 function getInterwikiLink( $key ) {
392 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
393 $fname = 'Title::getInterwikiLink';
394
395 wfProfileIn( $fname );
396
397 $k = $wgDBname.':interwiki:'.$key;
398 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
399 wfProfileOut( $fname );
400 return $wgTitleInterwikiCache[$k]->iw_url;
401 }
402
403 $s = $wgMemc->get( $k );
404 # Ignore old keys with no iw_local
405 if( $s && isset( $s->iw_local ) ) {
406 $wgTitleInterwikiCache[$k] = $s;
407 wfProfileOut( $fname );
408 return $s->iw_url;
409 }
410
411 $dbr =& wfGetDB( DB_SLAVE );
412 $res = $dbr->select( 'interwiki',
413 array( 'iw_url', 'iw_local' ),
414 array( 'iw_prefix' => $key ), $fname );
415 if( !$res ) {
416 wfProfileOut( $fname );
417 return '';
418 }
419
420 $s = $dbr->fetchObject( $res );
421 if( !$s ) {
422 # Cache non-existence: create a blank object and save it to memcached
423 $s = (object)false;
424 $s->iw_url = '';
425 $s->iw_local = 0;
426 }
427 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
428 $wgTitleInterwikiCache[$k] = $s;
429
430 wfProfileOut( $fname );
431 return $s->iw_url;
432 }
433
434 /**
435 * Determine whether the object refers to a page within
436 * this project.
437 *
438 * @return bool TRUE if this is an in-project interwiki link
439 * or a wikilink, FALSE otherwise
440 * @access public
441 */
442 function isLocal() {
443 global $wgTitleInterwikiCache, $wgDBname;
444
445 if ( $this->mInterwiki != '' ) {
446 # Make sure key is loaded into cache
447 $this->getInterwikiLink( $this->mInterwiki );
448 $k = $wgDBname.':interwiki:' . $this->mInterwiki;
449 return (bool)($wgTitleInterwikiCache[$k]->iw_local);
450 } else {
451 return true;
452 }
453 }
454
455 /**
456 * Update the page_touched field for an array of title objects
457 * @todo Inefficient unless the IDs are already loaded into the
458 * link cache
459 * @param array $titles an array of Title objects to be touched
460 * @param string $timestamp the timestamp to use instead of the
461 * default current time
462 * @static
463 * @access public
464 */
465 /* static */ function touchArray( $titles, $timestamp = '' ) {
466 if ( count( $titles ) == 0 ) {
467 return;
468 }
469 $dbw =& wfGetDB( DB_MASTER );
470 if ( $timestamp == '' ) {
471 $timestamp = $dbw->timestamp();
472 }
473 $page = $dbw->tableName( 'page' );
474 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
475 $first = true;
476
477 foreach ( $titles as $title ) {
478 if ( ! $first ) {
479 $sql .= ',';
480 }
481 $first = false;
482 $sql .= $title->getArticleID();
483 }
484 $sql .= ')';
485 if ( ! $first ) {
486 $dbw->query( $sql, 'Title::touchArray' );
487 }
488 }
489
490 #----------------------------------------------------------------------------
491 # Other stuff
492 #----------------------------------------------------------------------------
493
494 /** Simple accessors */
495 /**
496 * Get the text form (spaces not underscores) of the main part
497 * @return string
498 * @access public
499 */
500 function getText() { return $this->mTextform; }
501 /**
502 * Get the URL-encoded form of the main part
503 * @return string
504 * @access public
505 */
506 function getPartialURL() { return $this->mUrlform; }
507 /**
508 * Get the main part with underscores
509 * @return string
510 * @access public
511 */
512 function getDBkey() { return $this->mDbkeyform; }
513 /**
514 * Get the namespace index, i.e. one of the NS_xxxx constants
515 * @return int
516 * @access public
517 */
518 function getNamespace() { return $this->mNamespace; }
519 /**
520 * Get the interwiki prefix (or null string)
521 * @return string
522 * @access public
523 */
524 function getInterwiki() { return $this->mInterwiki; }
525 /**
526 * Get the Title fragment (i.e. the bit after the #)
527 * @return string
528 * @access public
529 */
530 function getFragment() { return $this->mFragment; }
531 /**
532 * Get the default namespace index, for when there is no namespace
533 * @return int
534 * @access public
535 */
536 function getDefaultNamespace() { return $this->mDefaultNamespace; }
537
538 /**
539 * Get title for search index
540 * @return string a stripped-down title string ready for the
541 * search index
542 */
543 function getIndexTitle() {
544 return Title::indexTitle( $this->mNamespace, $this->mTextform );
545 }
546
547 /**
548 * Get the prefixed database key form
549 * @return string the prefixed title, with underscores and
550 * any interwiki and namespace prefixes
551 * @access public
552 */
553 function getPrefixedDBkey() {
554 $s = $this->prefix( $this->mDbkeyform );
555 $s = str_replace( ' ', '_', $s );
556 return $s;
557 }
558
559 /**
560 * Get the prefixed title with spaces.
561 * This is the form usually used for display
562 * @return string the prefixed title, with spaces
563 * @access public
564 */
565 function getPrefixedText() {
566 global $wgContLang;
567 if ( empty( $this->mPrefixedText ) ) {
568 $s = $this->prefix( $this->mTextform );
569 $s = str_replace( '_', ' ', $s );
570 $this->mPrefixedText = $s;
571 }
572 return $this->mPrefixedText;
573 }
574
575 /**
576 * Get the prefixed title with spaces, plus any fragment
577 * (part beginning with '#')
578 * @return string the prefixed title, with spaces and
579 * the fragment, including '#'
580 * @access public
581 */
582 function getFullText() {
583 global $wgContLang;
584 $text = $this->getPrefixedText();
585 if( '' != $this->mFragment ) {
586 $text .= '#' . $this->mFragment;
587 }
588 return $text;
589 }
590
591 /**
592 * Get a URL-encoded title (not an actual URL) including interwiki
593 * @return string the URL-encoded form
594 * @access public
595 */
596 function getPrefixedURL() {
597 $s = $this->prefix( $this->mDbkeyform );
598 $s = str_replace( ' ', '_', $s );
599
600 $s = wfUrlencode ( $s ) ;
601
602 # Cleaning up URL to make it look nice -- is this safe?
603 $s = str_replace( '%28', '(', $s );
604 $s = str_replace( '%29', ')', $s );
605
606 return $s;
607 }
608
609 /**
610 * Get a real URL referring to this title, with interwiki link and
611 * fragment
612 *
613 * @param string $query an optional query string, not used
614 * for interwiki links
615 * @return string the URL
616 * @access public
617 */
618 function getFullURL( $query = '' ) {
619 global $wgContLang, $wgServer, $wgScript;
620
621 if ( '' == $this->mInterwiki ) {
622 return $wgServer . $this->getLocalUrl( $query );
623 } else {
624 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
625 $namespace = $wgContLang->getNsText( $this->mNamespace );
626 if ( '' != $namespace ) {
627 # Can this actually happen? Interwikis shouldn't be parsed.
628 $namepace .= ':';
629 }
630 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
631 if( $query != '' ) {
632 if( false === strpos( $url, '?' ) ) {
633 $url .= '?';
634 } else {
635 $url .= '&';
636 }
637 $url .= $query;
638 }
639 if ( '' != $this->mFragment ) {
640 $url .= '#' . $this->mFragment;
641 }
642 return $url;
643 }
644 }
645
646 /**
647 * Get a relative directory for putting an HTML version of this article into
648 */
649 function getHashedDirectory() {
650 $dbkey = $this->getPrefixedDBkey();
651 if ( strlen( $dbkey ) < 2 ) {
652 $dbkey = sprintf( "%2s", $dbkey );
653 }
654 $dir = '';
655 for ( $i=0; $i<=1; $i++ ) {
656 if ( $i ) {
657 $dir .= '/';
658 }
659 if ( ord( $dbkey{$i} ) < 128 && ord( $dbkey{$i} ) > 32 ) {
660 $dir .= strtolower( $dbkey{$i} );
661 } else {
662 $dir .= sprintf( "%02X", ord( $dbkey{$i} ) );
663 }
664 }
665 return $dir;
666 }
667
668 function getHashedFilename() {
669 $dbkey = $this->getPrefixedDBkey();
670 $dir = $this->getHashedDirectory();
671 $friendlyName = strtr( $dbkey, '/\\:*?"<>|', '_________' );
672 return "$dir/$friendlyName.html";
673 }
674
675 /**
676 * Get a URL with no fragment or server name
677 * @param string $query an optional query string; if not specified,
678 * $wgArticlePath will be used.
679 * @return string the URL
680 * @access public
681 */
682 function getLocalURL( $query = '' ) {
683 global $wgLang, $wgArticlePath, $wgScript, $wgMakeDumpLinks;
684
685 if ( $this->isExternal() ) {
686 return $this->getFullURL();
687 }
688
689 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
690 if ( $wgMakeDumpLinks ) {
691 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename() ), $wgArticlePath );
692 } elseif ( $query == '' ) {
693 $url = str_replace( '$1', $dbkey, $wgArticlePath );
694 } else {
695 if( preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) ) {
696 global $wgActionPaths;
697 $action = urldecode( $matches[2] );
698 if( isset( $wgActionPaths[$action] ) ) {
699 $query = $matches[1];
700 if( isset( $matches[4] ) ) $query .= $matches[4];
701 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
702 if( $query != '' ) $url .= '?' . $query;
703 return $url;
704 }
705 }
706 if ( $query == '-' ) {
707 $query = '';
708 }
709 $url = "{$wgScript}?title={$dbkey}&{$query}";
710 }
711 return $url;
712 }
713
714 /**
715 * Get an HTML-escaped version of the URL form, suitable for
716 * using in a link, without a server name or fragment
717 * @param string $query an optional query string
718 * @return string the URL
719 * @access public
720 */
721 function escapeLocalURL( $query = '' ) {
722 return htmlspecialchars( $this->getLocalURL( $query ) );
723 }
724
725 /**
726 * Get an HTML-escaped version of the URL form, suitable for
727 * using in a link, including the server name and fragment
728 *
729 * @return string the URL
730 * @param string $query an optional query string
731 * @access public
732 */
733 function escapeFullURL( $query = '' ) {
734 return htmlspecialchars( $this->getFullURL( $query ) );
735 }
736
737 /**
738 * Get the URL form for an internal link.
739 * - Used in various Squid-related code, in case we have a different
740 * internal hostname for the server from the exposed one.
741 *
742 * @param string $query an optional query string
743 * @return string the URL
744 * @access public
745 */
746 function getInternalURL( $query = '' ) {
747 global $wgInternalServer;
748 return $wgInternalServer . $this->getLocalURL( $query );
749 }
750
751 /**
752 * Get the edit URL for this Title
753 * @return string the URL, or a null string if this is an
754 * interwiki link
755 * @access public
756 */
757 function getEditURL() {
758 global $wgServer, $wgScript;
759
760 if ( '' != $this->mInterwiki ) { return ''; }
761 $s = $this->getLocalURL( 'action=edit' );
762
763 return $s;
764 }
765
766 /**
767 * Get the HTML-escaped displayable text form.
768 * Used for the title field in <a> tags.
769 * @return string the text, including any prefixes
770 * @access public
771 */
772 function getEscapedText() {
773 return htmlspecialchars( $this->getPrefixedText() );
774 }
775
776 /**
777 * Is this Title interwiki?
778 * @return boolean
779 * @access public
780 */
781 function isExternal() { return ( '' != $this->mInterwiki ); }
782
783 /**
784 * Does the title correspond to a protected article?
785 * @param string $what the action the page is protected from,
786 * by default checks move and edit
787 * @return boolean
788 * @access public
789 */
790 function isProtected($action = '') {
791 if ( -1 == $this->mNamespace ) { return true; }
792 if($action == 'edit' || $action == '') {
793 $a = $this->getRestrictions("edit");
794 if ( in_array( 'sysop', $a ) ) { return true; }
795 }
796 if($action == 'move' || $action == '') {
797 $a = $this->getRestrictions("move");
798 if ( in_array( 'sysop', $a ) ) { return true; }
799 }
800 return false;
801 }
802
803 /**
804 * Is $wgUser is watching this page?
805 * @return boolean
806 * @access public
807 */
808 function userIsWatching() {
809 global $wgUser;
810
811 if ( -1 == $this->mNamespace ) { return false; }
812 if ( 0 == $wgUser->getID() ) { return false; }
813
814 return $wgUser->isWatched( $this );
815 }
816
817 /**
818 * Is $wgUser perform $action this page?
819 * @param string $action action that permission needs to be checked for
820 * @return boolean
821 * @access private
822 */
823 function userCan($action) {
824 $fname = 'Title::userCanEdit';
825 wfProfileIn( $fname );
826
827 global $wgUser;
828 if( NS_SPECIAL == $this->mNamespace ) {
829 wfProfileOut( $fname );
830 return false;
831 }
832 if( NS_MEDIAWIKI == $this->mNamespace &&
833 !$wgUser->isAllowed('editinterface') ) {
834 wfProfileOut( $fname );
835 return false;
836 }
837 if( $this->mDbkeyform == '_' ) {
838 # FIXME: Is this necessary? Shouldn't be allowed anyway...
839 wfProfileOut( $fname );
840 return false;
841 }
842
843 # protect global styles and js
844 if ( NS_MEDIAWIKI == $this->mNamespace
845 && preg_match("/\\.(css|js)$/", $this->mTextform )
846 && !$wgUser->isAllowed('editinterface') ) {
847 wfProfileOut( $fname );
848 return false;
849 }
850
851 # protect css/js subpages of user pages
852 # XXX: this might be better using restrictions
853 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
854 if( NS_USER == $this->mNamespace
855 && preg_match("/\\.(css|js)$/", $this->mTextform )
856 && !$wgUser->isAllowed('editinterface')
857 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) ) {
858 wfProfileOut( $fname );
859 return false;
860 }
861
862 foreach( $this->getRestrictions($action) as $right ) {
863 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
864 wfProfileOut( $fname );
865 return false;
866 }
867 }
868
869 if( $action == 'move' && !$this->isMovable() ) {
870 wfProfileOut( $fname );
871 return false;
872 }
873
874 wfProfileOut( $fname );
875 return true;
876 }
877
878 /**
879 * Can $wgUser edit this page?
880 * @return boolean
881 * @access public
882 */
883 function userCanEdit() {
884 return $this->userCan('edit');
885 }
886
887 /**
888 * Can $wgUser move this page?
889 * @return boolean
890 * @access public
891 */
892 function userCanMove() {
893 return $this->userCan('move');
894 }
895
896 /**
897 * Would anybody with sufficient privileges be able to mvoe this page?
898 * Some pages just ain't movable.
899 *
900 * @return boolean
901 * @access public
902 */
903 function isMovable() {
904 return Namespace::isMovable( $this->getNamespace() )
905 && $this->getInterwiki() == '';
906 }
907
908 /**
909 * Can $wgUser read this page?
910 * @return boolean
911 * @access public
912 */
913 function userCanRead() {
914 global $wgUser;
915
916 if( $wgUser->isAllowed('read') ) {
917 return true;
918 } else {
919 global $wgWhitelistRead;
920
921 /** If anon users can create an account,
922 they need to reach the login page first! */
923 if( $wgUser->isAllowed( 'createaccount' )
924 && $this->mId == NS_SPECIAL
925 && $this->getText() == 'Userlogin' ) {
926 return true;
927 }
928
929 /** some pages are explicitly allowed */
930 $name = $this->getPrefixedText();
931 if( in_array( $name, $wgWhitelistRead ) ) {
932 return true;
933 }
934
935 # Compatibility with old settings
936 if( $this->getNamespace() == NS_MAIN ) {
937 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
938 return true;
939 }
940 }
941 }
942 return false;
943 }
944
945 /**
946 * Is this a talk page of some sort?
947 * @return bool
948 * @access public
949 */
950 function isTalkPage() {
951 return Namespace::isTalk( $this->getNamespace() );
952 }
953
954 /**
955 * Is this a .css or .js subpage of a user page?
956 * @return bool
957 * @access public
958 */
959 function isCssJsSubpage() {
960 return ( NS_USER == $this->mNamespace and preg_match("/\\.(css|js)$/", $this->mTextform ) );
961 }
962 /**
963 * Is this a .css subpage of a user page?
964 * @return bool
965 * @access public
966 */
967 function isCssSubpage() {
968 return ( NS_USER == $this->mNamespace and preg_match("/\\.css$/", $this->mTextform ) );
969 }
970 /**
971 * Is this a .js subpage of a user page?
972 * @return bool
973 * @access public
974 */
975 function isJsSubpage() {
976 return ( NS_USER == $this->mNamespace and preg_match("/\\.js$/", $this->mTextform ) );
977 }
978 /**
979 * Protect css/js subpages of user pages: can $wgUser edit
980 * this page?
981 *
982 * @return boolean
983 * @todo XXX: this might be better using restrictions
984 * @access public
985 */
986 function userCanEditCssJsSubpage() {
987 global $wgUser;
988 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
989 }
990
991 /**
992 * Loads a string into mRestrictions array
993 * @param string $res restrictions in string format
994 * @access public
995 */
996 function loadRestrictions( $res ) {
997 foreach( explode( ':', trim( $res ) ) as $restrict ) {
998 $temp = explode( '=', trim( $restrict ) );
999 if(count($temp) == 1) {
1000 // old format should be treated as edit/move restriction
1001 $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) );
1002 $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) );
1003 } else {
1004 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1005 }
1006 }
1007 $this->mRestrictionsLoaded = true;
1008 }
1009
1010 /**
1011 * Accessor/initialisation for mRestrictions
1012 * @param string $action action that permission needs to be checked for
1013 * @return array the array of groups allowed to edit this article
1014 * @access public
1015 */
1016 function getRestrictions($action) {
1017 $id = $this->getArticleID();
1018 if ( 0 == $id ) { return array(); }
1019
1020 if ( ! $this->mRestrictionsLoaded ) {
1021 $dbr =& wfGetDB( DB_SLAVE );
1022 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1023 $this->loadRestrictions( $res );
1024 }
1025 if( isset( $this->mRestrictions[$action] ) ) {
1026 return $this->mRestrictions[$action];
1027 }
1028 return array();
1029 }
1030
1031 /**
1032 * Is there a version of this page in the deletion archive?
1033 * @return int the number of archived revisions
1034 * @access public
1035 */
1036 function isDeleted() {
1037 $fname = 'Title::isDeleted';
1038 $dbr =& wfGetDB( DB_SLAVE );
1039 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1040 'ar_title' => $this->getDBkey() ), $fname );
1041 return (int)$n;
1042 }
1043
1044 /**
1045 * Get the article ID for this Title from the link cache,
1046 * adding it if necessary
1047 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1048 * for update
1049 * @return int the ID
1050 * @access public
1051 */
1052 function getArticleID( $flags = 0 ) {
1053 global $wgLinkCache;
1054
1055 if ( $flags & GAID_FOR_UPDATE ) {
1056 $oldUpdate = $wgLinkCache->forUpdate( true );
1057 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
1058 $wgLinkCache->forUpdate( $oldUpdate );
1059 } else {
1060 if ( -1 == $this->mArticleID ) {
1061 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
1062 }
1063 }
1064 return $this->mArticleID;
1065 }
1066
1067 /**
1068 * This clears some fields in this object, and clears any associated
1069 * keys in the "bad links" section of $wgLinkCache.
1070 *
1071 * - This is called from Article::insertNewArticle() to allow
1072 * loading of the new page_id. It's also called from
1073 * Article::doDeleteArticle()
1074 *
1075 * @param int $newid the new Article ID
1076 * @access public
1077 */
1078 function resetArticleID( $newid ) {
1079 global $wgLinkCache;
1080 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
1081
1082 if ( 0 == $newid ) { $this->mArticleID = -1; }
1083 else { $this->mArticleID = $newid; }
1084 $this->mRestrictionsLoaded = false;
1085 $this->mRestrictions = array();
1086 }
1087
1088 /**
1089 * Updates page_touched for this page; called from LinksUpdate.php
1090 * @return bool true if the update succeded
1091 * @access public
1092 */
1093 function invalidateCache() {
1094 if ( wfReadOnly() ) {
1095 return;
1096 }
1097
1098 $now = wfTimestampNow();
1099 $dbw =& wfGetDB( DB_MASTER );
1100 $success = $dbw->update( 'page',
1101 array( /* SET */
1102 'page_touched' => $dbw->timestamp()
1103 ), array( /* WHERE */
1104 'page_namespace' => $this->getNamespace() ,
1105 'page_title' => $this->getDBkey()
1106 ), 'Title::invalidateCache'
1107 );
1108 return $success;
1109 }
1110
1111 /**
1112 * Prefix some arbitrary text with the namespace or interwiki prefix
1113 * of this object
1114 *
1115 * @param string $name the text
1116 * @return string the prefixed text
1117 * @access private
1118 */
1119 /* private */ function prefix( $name ) {
1120 global $wgContLang;
1121
1122 $p = '';
1123 if ( '' != $this->mInterwiki ) {
1124 $p = $this->mInterwiki . ':';
1125 }
1126 if ( 0 != $this->mNamespace ) {
1127 $p .= $wgContLang->getNsText( $this->mNamespace ) . ':';
1128 }
1129 return $p . $name;
1130 }
1131
1132 /**
1133 * Secure and split - main initialisation function for this object
1134 *
1135 * Assumes that mDbkeyform has been set, and is urldecoded
1136 * and uses underscores, but not otherwise munged. This function
1137 * removes illegal characters, splits off the interwiki and
1138 * namespace prefixes, sets the other forms, and canonicalizes
1139 * everything.
1140 * @return bool true on success
1141 * @access private
1142 */
1143 /* private */ function secureAndSplit() {
1144 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1145 $fname = 'Title::secureAndSplit';
1146 wfProfileIn( $fname );
1147
1148 # Initialisation
1149 static $rxTc = false;
1150 if( !$rxTc ) {
1151 # % is needed as well
1152 $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1153 }
1154
1155 $this->mInterwiki = $this->mFragment = '';
1156 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1157
1158 # Clean up whitespace
1159 #
1160 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform );
1161 $t = trim( $t, '_' );
1162
1163 if ( '' == $t ) {
1164 wfProfileOut( $fname );
1165 return false;
1166 }
1167
1168 if( false !== strpos( $t, UTF8_REPLACEMENT ) ) {
1169 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1170 wfProfileOut( $fname );
1171 return false;
1172 }
1173
1174 $this->mDbkeyform = $t;
1175
1176 # Initial colon indicating main namespace
1177 if ( ':' == $t{0} ) {
1178 $r = substr( $t, 1 );
1179 $this->mNamespace = NS_MAIN;
1180 } else {
1181 # Namespace or interwiki prefix
1182 $firstPass = true;
1183 do {
1184 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1185 $p = $m[1];
1186 $lowerNs = strtolower( $p );
1187 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1188 # Canonical namespace
1189 $t = $m[2];
1190 $this->mNamespace = $ns;
1191 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1192 # Ordinary namespace
1193 $t = $m[2];
1194 $this->mNamespace = $ns;
1195 } elseif( $this->getInterwikiLink( $p ) ) {
1196 if( !$firstPass ) {
1197 # Can't make a local interwiki link to an interwiki link.
1198 # That's just crazy!
1199 wfProfileOut( $fname );
1200 return false;
1201 }
1202
1203 # Interwiki link
1204 $t = $m[2];
1205 $this->mInterwiki = $p;
1206
1207 # Redundant interwiki prefix to the local wiki
1208 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1209 if( $t == '' ) {
1210 # Can't have an empty self-link
1211 wfProfileOut( $fname );
1212 return false;
1213 }
1214 $this->mInterwiki = '';
1215 $firstPass = false;
1216 # Do another namespace split...
1217 continue;
1218 }
1219 }
1220 # If there's no recognized interwiki or namespace,
1221 # then let the colon expression be part of the title.
1222 }
1223 break;
1224 } while( true );
1225 $r = $t;
1226 }
1227
1228 # We already know that some pages won't be in the database!
1229 #
1230 if ( '' != $this->mInterwiki || -1 == $this->mNamespace ) {
1231 $this->mArticleID = 0;
1232 }
1233 $f = strstr( $r, '#' );
1234 if ( false !== $f ) {
1235 $this->mFragment = substr( $f, 1 );
1236 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1237 # remove whitespace again: prevents "Foo_bar_#"
1238 # becoming "Foo_bar_"
1239 $r = preg_replace( '/_*$/', '', $r );
1240 }
1241
1242 # Reject illegal characters.
1243 #
1244 if( preg_match( $rxTc, $r ) ) {
1245 wfProfileOut( $fname );
1246 return false;
1247 }
1248
1249 /**
1250 * Pages with "/./" or "/../" appearing in the URLs will
1251 * often be unreachable due to the way web browsers deal
1252 * with 'relative' URLs. Forbid them explicitly.
1253 */
1254 if ( strpos( $r, '.' ) !== false &&
1255 ( $r === '.' || $r === '..' ||
1256 strpos( $r, './' ) === 0 ||
1257 strpos( $r, '../' ) === 0 ||
1258 strpos( $r, '/./' ) !== false ||
1259 strpos( $r, '/../' ) !== false ) )
1260 {
1261 wfProfileOut( $fname );
1262 return false;
1263 }
1264
1265 # We shouldn't need to query the DB for the size.
1266 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1267 if ( strlen( $r ) > 255 ) {
1268 wfProfileOut( $fname );
1269 return false;
1270 }
1271
1272 /**
1273 * Normally, all wiki links are forced to have
1274 * an initial capital letter so [[foo]] and [[Foo]]
1275 * point to the same place.
1276 *
1277 * Don't force it for interwikis, since the other
1278 * site might be case-sensitive.
1279 */
1280 if( $wgCapitalLinks && $this->mInterwiki == '') {
1281 $t = $wgContLang->ucfirst( $r );
1282 } else {
1283 $t = $r;
1284 }
1285
1286 /**
1287 * Can't make a link to a namespace alone...
1288 * "empty" local links can only be self-links
1289 * with a fragment identifier.
1290 */
1291 if( $t == '' &&
1292 $this->mInterwiki == '' &&
1293 $this->mNamespace != NS_MAIN ) {
1294 wfProfileOut( $fname );
1295 return false;
1296 }
1297
1298 # Fill fields
1299 $this->mDbkeyform = $t;
1300 $this->mUrlform = wfUrlencode( $t );
1301
1302 $this->mTextform = str_replace( '_', ' ', $t );
1303
1304 wfProfileOut( $fname );
1305 return true;
1306 }
1307
1308 /**
1309 * Get a Title object associated with the talk page of this article
1310 * @return Title the object for the talk page
1311 * @access public
1312 */
1313 function getTalkPage() {
1314 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1315 }
1316
1317 /**
1318 * Get a title object associated with the subject page of this
1319 * talk page
1320 *
1321 * @return Title the object for the subject page
1322 * @access public
1323 */
1324 function getSubjectPage() {
1325 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1326 }
1327
1328 /**
1329 * Get an array of Title objects linking to this Title
1330 * - Also stores the IDs in the link cache.
1331 *
1332 * @param string $options may be FOR UPDATE
1333 * @return array the Title objects linking here
1334 * @access public
1335 */
1336 function getLinksTo( $options = '' ) {
1337 global $wgLinkCache;
1338 $id = $this->getArticleID();
1339
1340 if ( $options ) {
1341 $db =& wfGetDB( DB_MASTER );
1342 } else {
1343 $db =& wfGetDB( DB_SLAVE );
1344 }
1345 $page = $db->tableName( 'page' );
1346 $links = $db->tableName( 'links' );
1347
1348 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$links WHERE l_from=page_id AND l_to={$id} $options";
1349 $res = $db->query( $sql, 'Title::getLinksTo' );
1350 $retVal = array();
1351 if ( $db->numRows( $res ) ) {
1352 while ( $row = $db->fetchObject( $res ) ) {
1353 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1354 $wgLinkCache->addGoodLink( $row->page_id, $titleObj->getPrefixedDBkey() );
1355 $retVal[] = $titleObj;
1356 }
1357 }
1358 }
1359 $db->freeResult( $res );
1360 return $retVal;
1361 }
1362
1363 /**
1364 * Get an array of Title objects linking to this non-existent title.
1365 * - Also stores the IDs in the link cache.
1366 *
1367 * @param string $options may be FOR UPDATE
1368 * @return array the Title objects linking here
1369 * @access public
1370 */
1371 function getBrokenLinksTo( $options = '' ) {
1372 global $wgLinkCache;
1373
1374 if ( $options ) {
1375 $db =& wfGetDB( DB_MASTER );
1376 } else {
1377 $db =& wfGetDB( DB_SLAVE );
1378 }
1379 $page = $db->tableName( 'page' );
1380 $brokenlinks = $db->tableName( 'brokenlinks' );
1381 $encTitle = $db->strencode( $this->getPrefixedDBkey() );
1382
1383 $sql = "SELECT page_namespace,page_title,page_id FROM $brokenlinks,$page " .
1384 "WHERE bl_from=page_id AND bl_to='$encTitle' $options";
1385 $res = $db->query( $sql, "Title::getBrokenLinksTo" );
1386 $retVal = array();
1387 if ( $db->numRows( $res ) ) {
1388 while ( $row = $db->fetchObject( $res ) ) {
1389 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
1390 $wgLinkCache->addGoodLink( $row->page_id, $titleObj->getPrefixedDBkey() );
1391 $retVal[] = $titleObj;
1392 }
1393 }
1394 $db->freeResult( $res );
1395 return $retVal;
1396 }
1397
1398
1399 /**
1400 * Get an array of Title objects referring to non-existent articles linked from this page
1401 *
1402 * @param string $options may be FOR UPDATE
1403 * @return array the Title objects
1404 * @access public
1405 */
1406 function getBrokenLinksFrom( $options = '' ) {
1407 global $wgLinkCache;
1408
1409 if ( $options ) {
1410 $db =& wfGetDB( DB_MASTER );
1411 } else {
1412 $db =& wfGetDB( DB_SLAVE );
1413 }
1414 $page = $db->tableName( 'page' );
1415 $brokenlinks = $db->tableName( 'brokenlinks' );
1416 $id = $this->getArticleID();
1417
1418 $sql = "SELECT bl_to FROM $brokenlinks WHERE bl_from=$id $options";
1419 $res = $db->query( $sql, "Title::getBrokenLinksFrom" );
1420 $retVal = array();
1421 if ( $db->numRows( $res ) ) {
1422 while ( $row = $db->fetchObject( $res ) ) {
1423 $retVal[] = Title::newFromText( $row->bl_to );
1424 }
1425 }
1426 $db->freeResult( $res );
1427 return $retVal;
1428 }
1429
1430
1431 /**
1432 * Get a list of URLs to purge from the Squid cache when this
1433 * page changes
1434 *
1435 * @return array the URLs
1436 * @access public
1437 */
1438 function getSquidURLs() {
1439 return array(
1440 $this->getInternalURL(),
1441 $this->getInternalURL( 'action=history' )
1442 );
1443 }
1444
1445 /**
1446 * Move this page without authentication
1447 * @param Title &$nt the new page Title
1448 * @access public
1449 */
1450 function moveNoAuth( &$nt ) {
1451 return $this->moveTo( $nt, false );
1452 }
1453
1454 /**
1455 * Check whether a given move operation would be valid.
1456 * Returns true if ok, or a message key string for an error message
1457 * if invalid. (Scarrrrry ugly interface this.)
1458 * @param Title &$nt the new title
1459 * @param bool $auth indicates whether $wgUser's permissions
1460 * should be checked
1461 * @return mixed true on success, message name on failure
1462 * @access public
1463 */
1464 function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
1465 global $wgUser;
1466 if( !$this or !$nt ) {
1467 return 'badtitletext';
1468 }
1469 if( $this->equals( $nt ) ) {
1470 return 'selfmove';
1471 }
1472 if( !$this->isMovable() || !$nt->isMovable() ) {
1473 return 'immobile_namespace';
1474 }
1475
1476 $fname = 'Title::move';
1477 $oldid = $this->getArticleID();
1478 $newid = $nt->getArticleID();
1479
1480 if ( strlen( $nt->getDBkey() ) < 1 ) {
1481 return 'articleexists';
1482 }
1483 if ( ( '' == $this->getDBkey() ) ||
1484 ( !$oldid ) ||
1485 ( '' == $nt->getDBkey() ) ) {
1486 return 'badarticleerror';
1487 }
1488
1489 if ( $auth && (
1490 !$this->userCanEdit() || !$nt->userCanEdit() ||
1491 !$this->userCanMove() || !$nt->userCanMove() ) ) {
1492 return 'protectedpage';
1493 }
1494
1495 # The move is allowed only if (1) the target doesn't exist, or
1496 # (2) the target is a redirect to the source, and has no history
1497 # (so we can undo bad moves right after they're done).
1498
1499 if ( 0 != $newid ) { # Target exists; check for validity
1500 if ( ! $this->isValidMoveTarget( $nt ) ) {
1501 return 'articleexists';
1502 }
1503 }
1504 return true;
1505 }
1506
1507 /**
1508 * Move a title to a new location
1509 * @param Title &$nt the new title
1510 * @param bool $auth indicates whether $wgUser's permissions
1511 * should be checked
1512 * @return mixed true on success, message name on failure
1513 * @access public
1514 */
1515 function moveTo( &$nt, $auth = true, $reason = '' ) {
1516 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
1517 if( is_string( $err ) ) {
1518 return $err;
1519 }
1520 if( $nt->exists() ) {
1521 $this->moveOverExistingRedirect( $nt, $reason );
1522 } else { # Target didn't exist, do normal move.
1523 $this->moveToNewTitle( $nt, $newid, $reason );
1524 }
1525
1526 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1527
1528 $dbw =& wfGetDB( DB_MASTER );
1529 $categorylinks = $dbw->tableName( 'categorylinks' );
1530 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1531 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
1532 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1533 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1534
1535 # Update watchlists
1536
1537 $oldnamespace = $this->getNamespace() & ~1;
1538 $newnamespace = $nt->getNamespace() & ~1;
1539 $oldtitle = $this->getDBkey();
1540 $newtitle = $nt->getDBkey();
1541
1542 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
1543 WatchedItem::duplicateEntries( $this, $nt );
1544 }
1545
1546 # Update search engine
1547 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
1548 $u->doUpdate();
1549 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), '' );
1550 $u->doUpdate();
1551
1552 wfRunHooks( 'TitleMoveComplete', array(&$this, &$nt, &$wgUser, $oldid, $newid) );
1553 return true;
1554 }
1555
1556 /**
1557 * Move page to a title which is at present a redirect to the
1558 * source page
1559 *
1560 * @param Title &$nt the page to move to, which should currently
1561 * be a redirect
1562 * @access private
1563 */
1564 /* private */ function moveOverExistingRedirect( &$nt, $reason = '' ) {
1565 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1566 $fname = 'Title::moveOverExistingRedirect';
1567 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1568
1569 if ( $reason ) {
1570 $comment .= ": $reason";
1571 }
1572
1573 $now = wfTimestampNow();
1574 $rand = wfRandom();
1575 $newid = $nt->getArticleID();
1576 $oldid = $this->getArticleID();
1577 $dbw =& wfGetDB( DB_MASTER );
1578 $links = $dbw->tableName( 'links' );
1579
1580 # Delete the old redirect. We don't save it to history since
1581 # by definition if we've got here it's rather uninteresting.
1582 # We have to remove it so that the next step doesn't trigger
1583 # a conflict on the unique namespace+title index...
1584 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1585
1586 # Save a null revision in the page's history notifying of the move
1587 $nullRevision = Revision::newNullRevision( $dbw, $oldid,
1588 wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1589 true );
1590 $nullRevId = $nullRevision->insertOn( $dbw );
1591
1592 # Change the name of the target page:
1593 $dbw->update( 'page',
1594 /* SET */ array(
1595 'page_touched' => $dbw->timestamp($now),
1596 'page_namespace' => $nt->getNamespace(),
1597 'page_title' => $nt->getDBkey(),
1598 'page_latest' => $nullRevId,
1599 ),
1600 /* WHERE */ array( 'page_id' => $oldid ),
1601 $fname
1602 );
1603 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1604
1605 # Recreate the redirect, this time in the other direction.
1606 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1607 $redirectArticle = new Article( $this );
1608 $newid = $redirectArticle->insertOn( $dbw );
1609 $redirectRevision = new Revision( array(
1610 'page' => $newid,
1611 'comment' => $comment,
1612 'text' => $redirectText ) );
1613 $revid = $redirectRevision->insertOn( $dbw );
1614 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1615 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1616
1617 # Log the move
1618 $log = new LogPage( 'move' );
1619 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1620
1621 # Swap links
1622
1623 # Load titles and IDs
1624 $linksToOld = $this->getLinksTo( 'FOR UPDATE' );
1625 $linksToNew = $nt->getLinksTo( 'FOR UPDATE' );
1626
1627 # Delete them all
1628 $sql = "DELETE FROM $links WHERE l_to=$oldid OR l_to=$newid";
1629 $dbw->query( $sql, $fname );
1630
1631 # Reinsert
1632 if ( count( $linksToOld ) || count( $linksToNew )) {
1633 $sql = "INSERT INTO $links (l_from,l_to) VALUES ";
1634 $first = true;
1635
1636 # Insert links to old title
1637 foreach ( $linksToOld as $linkTitle ) {
1638 if ( $first ) {
1639 $first = false;
1640 } else {
1641 $sql .= ',';
1642 }
1643 $id = $linkTitle->getArticleID();
1644 $sql .= "($id,$newid)";
1645 }
1646
1647 # Insert links to new title
1648 foreach ( $linksToNew as $linkTitle ) {
1649 if ( $first ) {
1650 $first = false;
1651 } else {
1652 $sql .= ',';
1653 }
1654 $id = $linkTitle->getArticleID();
1655 $sql .= "($id, $oldid)";
1656 }
1657
1658 $dbw->query( $sql, $fname );
1659 }
1660
1661 # Now, we record the link from the redirect to the new title.
1662 # It should have no other outgoing links...
1663 $dbw->delete( 'links', array( 'l_from' => $newid ) );
1664 $dbw->insert( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ) );
1665
1666 # Clear linkscc
1667 LinkCache::linksccClearLinksTo( $oldid );
1668 LinkCache::linksccClearLinksTo( $newid );
1669
1670 # Purge squid
1671 if ( $wgUseSquid ) {
1672 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1673 $u = new SquidUpdate( $urls );
1674 $u->doUpdate();
1675 }
1676 }
1677
1678 /**
1679 * Move page to non-existing title.
1680 * @param Title &$nt the new Title
1681 * @param int &$newid set to be the new article ID
1682 * @access private
1683 */
1684 /* private */ function moveToNewTitle( &$nt, &$newid, $reason = '' ) {
1685 global $wgUser, $wgLinkCache, $wgUseSquid;
1686 global $wgMwRedir;
1687 $fname = 'MovePageForm::moveToNewTitle';
1688 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1689 if ( $reason ) {
1690 $comment .= ": $reason";
1691 }
1692
1693 $newid = $nt->getArticleID();
1694 $oldid = $this->getArticleID();
1695 $dbw =& wfGetDB( DB_MASTER );
1696 $now = $dbw->timestamp();
1697 wfSeedRandom();
1698 $rand = wfRandom();
1699
1700 # Save a null revision in the page's history notifying of the move
1701 $nullRevision = Revision::newNullRevision( $dbw, $oldid,
1702 wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1703 true );
1704 $nullRevId = $nullRevision->insertOn( $dbw );
1705
1706 # Rename cur entry
1707 $dbw->update( 'page',
1708 /* SET */ array(
1709 'page_touched' => $now,
1710 'page_namespace' => $nt->getNamespace(),
1711 'page_title' => $nt->getDBkey(),
1712 'page_latest' => $nullRevId,
1713 ),
1714 /* WHERE */ array( 'page_id' => $oldid ),
1715 $fname
1716 );
1717
1718 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1719
1720 # Insert redirect
1721 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1722 $redirectArticle = new Article( $this );
1723 $newid = $redirectArticle->insertOn( $dbw );
1724 $redirectRevision = new Revision( array(
1725 'page' => $newid,
1726 'comment' => $comment,
1727 'text' => $redirectText ) );
1728 $revid = $redirectRevision->insertOn( $dbw );
1729 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1730 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1731
1732 # Log the move
1733 $log = new LogPage( 'move' );
1734 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1735
1736 # Purge squid and linkscc as per article creation
1737 Article::onArticleCreate( $nt );
1738
1739 # Any text links to the old title must be reassigned to the redirect
1740 $dbw->update( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1741 LinkCache::linksccClearLinksTo( $oldid );
1742
1743 # Record the just-created redirect's linking to the page
1744 $dbw->insert( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1745
1746 # Non-existent target may have had broken links to it; these must
1747 # now be removed and made into good links.
1748 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1749 $update->fixBrokenLinks();
1750
1751 # Purge old title from squid
1752 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1753 $titles = $nt->getLinksTo();
1754 if ( $wgUseSquid ) {
1755 $urls = $this->getSquidURLs();
1756 foreach ( $titles as $linkTitle ) {
1757 $urls[] = $linkTitle->getInternalURL();
1758 }
1759 $u = new SquidUpdate( $urls );
1760 $u->doUpdate();
1761 }
1762 }
1763
1764 /**
1765 * Checks if $this can be moved to a given Title
1766 * - Selects for update, so don't call it unless you mean business
1767 *
1768 * @param Title &$nt the new title to check
1769 * @access public
1770 */
1771 function isValidMoveTarget( $nt ) {
1772
1773 $fname = 'Title::isValidMoveTarget';
1774 $dbw =& wfGetDB( DB_MASTER );
1775
1776 # Is it a redirect?
1777 $id = $nt->getArticleID();
1778 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1779 array( 'page_is_redirect','old_text' ),
1780 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1781 $fname, 'FOR UPDATE' );
1782
1783 if ( !$obj || 0 == $obj->page_is_redirect ) {
1784 # Not a redirect
1785 return false;
1786 }
1787
1788 # Does the redirect point to the source?
1789 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->old_text, $m ) ) {
1790 $redirTitle = Title::newFromText( $m[1] );
1791 if( !is_object( $redirTitle ) ||
1792 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1793 return false;
1794 }
1795 }
1796
1797 # Does the article have a history?
1798 $row = $dbw->selectRow( array( 'page', 'revision'),
1799 array( 'rev_id' ),
1800 array( 'page_namespace' => $nt->getNamespace(),
1801 'page_title' => $nt->getDBkey(),
1802 'page_id=rev_page AND page_latest != rev_id'
1803 ), $fname, 'FOR UPDATE'
1804 );
1805
1806 # Return true if there was no history
1807 return $row === false;
1808 }
1809
1810 /**
1811 * Create a redirect; fails if the title already exists; does
1812 * not notify RC
1813 *
1814 * @param Title $dest the destination of the redirect
1815 * @param string $comment the comment string describing the move
1816 * @return bool true on success
1817 * @access public
1818 */
1819 function createRedirect( $dest, $comment ) {
1820 global $wgUser;
1821 if ( $this->getArticleID() ) {
1822 return false;
1823 }
1824
1825 $fname = 'Title::createRedirect';
1826 $dbw =& wfGetDB( DB_MASTER );
1827
1828 $article = new Article( $this );
1829 $newid = $article->insertOn( $dbw );
1830 $revision = new Revision( array(
1831 'page' => $newid,
1832 'comment' => $comment,
1833 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1834 ) );
1835 $revisionId = $revision->insertOn( $dbw );
1836 $article->updateRevisionOn( $dbw, $revision, 0 );
1837
1838 # Link table
1839 if ( $dest->getArticleID() ) {
1840 $dbw->insert( 'links',
1841 array(
1842 'l_to' => $dest->getArticleID(),
1843 'l_from' => $newid
1844 ), $fname
1845 );
1846 } else {
1847 $dbw->insert( 'brokenlinks',
1848 array(
1849 'bl_to' => $dest->getPrefixedDBkey(),
1850 'bl_from' => $newid
1851 ), $fname
1852 );
1853 }
1854
1855 Article::onArticleCreate( $this );
1856 return true;
1857 }
1858
1859 /**
1860 * Get categories to which this Title belongs and return an array of
1861 * categories' names.
1862 *
1863 * @return array an array of parents in the form:
1864 * $parent => $currentarticle
1865 * @access public
1866 */
1867 function getParentCategories() {
1868 global $wgContLang,$wgUser;
1869
1870 $titlekey = $this->getArticleId();
1871 $sk =& $wgUser->getSkin();
1872 $parents = array();
1873 $dbr =& wfGetDB( DB_SLAVE );
1874 $categorylinks = $dbr->tableName( 'categorylinks' );
1875
1876 # NEW SQL
1877 $sql = "SELECT * FROM $categorylinks"
1878 ." WHERE cl_from='$titlekey'"
1879 ." AND cl_from <> '0'"
1880 ." ORDER BY cl_sortkey";
1881
1882 $res = $dbr->query ( $sql ) ;
1883
1884 if($dbr->numRows($res) > 0) {
1885 while ( $x = $dbr->fetchObject ( $res ) )
1886 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1887 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
1888 $dbr->freeResult ( $res ) ;
1889 } else {
1890 $data = '';
1891 }
1892 return $data;
1893 }
1894
1895 /**
1896 * Get a tree of parent categories
1897 * @param array $children an array with the children in the keys, to check for circular refs
1898 * @return array
1899 * @access public
1900 */
1901 function getParentCategoryTree( $children = array() ) {
1902 $parents = $this->getParentCategories();
1903
1904 if($parents != '') {
1905 foreach($parents as $parent => $current)
1906 {
1907 if ( array_key_exists( $parent, $children ) ) {
1908 # Circular reference
1909 $stack[$parent] = array();
1910 } else {
1911 $nt = Title::newFromText($parent);
1912 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
1913 }
1914 }
1915 return $stack;
1916 } else {
1917 return array();
1918 }
1919 }
1920
1921
1922 /**
1923 * Get an associative array for selecting this title from
1924 * the "cur" table
1925 *
1926 * @return array
1927 * @access public
1928 */
1929 function curCond() {
1930 wfDebugDieBacktrace( 'curCond called' );
1931 return array( 'cur_namespace' => $this->mNamespace, 'cur_title' => $this->mDbkeyform );
1932 }
1933
1934 /**
1935 * Get an associative array for selecting this title from the
1936 * "old" table
1937 *
1938 * @return array
1939 * @access public
1940 */
1941 function oldCond() {
1942 wfDebugDieBacktrace( 'oldCond called' );
1943 return array( 'old_namespace' => $this->mNamespace, 'old_title' => $this->mDbkeyform );
1944 }
1945
1946 /**
1947 * Get the revision ID of the previous revision
1948 *
1949 * @param integer $revision Revision ID. Get the revision that was before this one.
1950 * @return interger $oldrevision|false
1951 */
1952 function getPreviousRevisionID( $revision ) {
1953 $dbr =& wfGetDB( DB_SLAVE );
1954 return $dbr->selectField( 'revision', 'rev_id',
1955 'rev_page=' . IntVal( $this->getArticleId() ) .
1956 ' AND rev_id<' . IntVal( $revision ) . ' ORDER BY rev_id DESC' );
1957 }
1958
1959 /**
1960 * Get the revision ID of the next revision
1961 *
1962 * @param integer $revision Revision ID. Get the revision that was after this one.
1963 * @return interger $oldrevision|false
1964 */
1965 function getNextRevisionID( $revision ) {
1966 $dbr =& wfGetDB( DB_SLAVE );
1967 return $dbr->selectField( 'revision', 'rev_id',
1968 'rev_page=' . IntVal( $this->getArticleId() ) .
1969 ' AND rev_id>' . IntVal( $revision ) . ' ORDER BY rev_id' );
1970 }
1971
1972 /**
1973 * Compare with another title.
1974 *
1975 * @param Title $title
1976 * @return bool
1977 */
1978 function equals( &$title ) {
1979 return $this->getInterwiki() == $title->getInterwiki()
1980 && $this->getNamespace() == $title->getNamespace()
1981 && $this->getDbkey() == $title->getDbkey();
1982 }
1983
1984 /**
1985 * Check if page exists
1986 * @return bool
1987 */
1988 function exists() {
1989 return $this->getArticleId() != 0;
1990 }
1991
1992 }
1993 ?>